package cn.jilian.common.service.sms;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;

import cn.jilian.common.service.SMSService;

@Service
@ConditionalOnProperty(prefix="sms.platform",name="provider",havingValue="chuanlan")
public class ChuanlanSmsService implements SMSService {

	
	/**
	 * 短信平台url
	 * */
	@Value("${sms.platform.url}")
	private String SMSURL;
	/**
	 * 短信平台账户名
	 * */
	@Value("${sms.platform.account}")
	private String SMSACCT;
	/**
	 * 短信平台密码
	 * */
	@Value("${sms.platform.pass}")
	private String SMSPASS;
	@Override
	public int sendSms(String tel, String content) {
		CloseableHttpClient httpclient=HttpClients.createDefault();
		HttpPost httppost = new HttpPost(SMSURL);
		 List<NameValuePair> params = new ArrayList<NameValuePair>();
         params.add(new BasicNameValuePair("account", SMSACCT));
         params.add(new BasicNameValuePair("pswd",SMSPASS));
         params.add(new BasicNameValuePair("mobile",tel));
         params.add(new BasicNameValuePair("msg",content));
         params.add(new BasicNameValuePair("needstatus","false"));
         params.add(new BasicNameValuePair("product",""));
         params.add(new BasicNameValuePair("extno",null));
         try {
        	httppost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
			httppost.setEntity(new UrlEncodedFormEntity(params,"UTF-8"));HttpResponse httpResponse=httpclient.execute(httppost);
       	 	String str= new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent())).readLine();
       	 	if(str.endsWith(",0"))return 0;
       	 	else return -1;
		} catch (Exception e) {
			e.printStackTrace();
			return -1;
		}finally{
			httppost.releaseConnection();
		}
	}
	@Override
	public int sendSmsCode(String tel, String templateId, String code) {
		// TODO Auto-generated method stub
		return 0;
	}

}
